package cn.com.gridinfo.sooc.core.my.setting.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.core.my.setting.adapter.ProQuestionAdapter;
import cn.com.gridinfo.sooc.core.my.setting.bean.GetQuestion;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;
import cn.com.gridinfo.sooc.utils.widget.WheelDialog;
import cn.com.gridinfo.sooc.utils.widget.widget.adapters.AbstractWheelTextAdapter;
import cn.com.gridinfo.sooc.utils.widget.widget.views.OnWheelChangedListener;
import cn.com.gridinfo.sooc.utils.widget.widget.views.OnWheelScrollListener;
import cn.com.gridinfo.sooc.utils.widget.widget.views.WheelView;

/**
 * 设置密保问题
 * Created by 刘晓晨 on 2015/12/16.
 */
public class MiBaoActivity extends BaseSoocActivity {
    @InjectView(R.id.question1)
    TextView question1;//  第一个密保问题
    @InjectView(R.id.question2)
    TextView question2;// 第二个问题
    @InjectView(R.id.question3)
    TextView question3;// 第三个问题
    @InjectView(R.id.btn_send)
    Button btnSend;// 提交按钮
    @InjectView(R.id.answer1)
    ClearEditText answer1;//回答1
    @InjectView(R.id.answer2)
    ClearEditText answer2;//回答2
    @InjectView(R.id.answer3)
    ClearEditText answer3;//回答3
    MyDao dao;//用户 dao
    private String[] questionIdArray = new String[]{"", "", ""};
    String q1 = "", q2 = "", q3 = "";//第1,2,3个密保问题选择的是list中第几个问题   默认为-1，即为没选择
    List<GetQuestion> mibaoQ = new ArrayList<>();//去重的list

    List<GetQuestion> getQuestionList = new ArrayList<>();
    CourseListAdapter adapter;//适配器
    String currentText;//当前选中文字
    private WheelView wv;
    int currentPosition;//当前显示的item
    int selectPosition;//选择的item

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_setting_mibao);
        ButterKnife.inject(this);
        dao = new MyDao(this);
        dao.getQuestion();//请求接口
        btnSend.setEnabled(false);
        answer3.setImeOptions(EditorInfo.IME_ACTION_DONE);
        answer3.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (validateNotNull()) {
                        setQuesion();
                    }

                }
                return false;
            }
        });

    }

    private boolean validateNotNull() {
        //问题一
        if (StringUtils.isNull(answer1.getText().toString().trim())) {
            answer1.requestFocus();
            return false;
        }
        //问题二
        if (StringUtils.isNull(answer2.getText().toString().trim())) {
            answer2.requestFocus();
            return false;
        }
        //问题三
        if (StringUtils.isNull(answer3.getText().toString().trim())) {
            answer3.requestFocus();
            return false;
        }
        return true;
    }

    // 点击选择问题 1
    @OnClick(R.id.selectQuestion1)
    void setSelectQuestion1() {
        mibaoQ.clear();
        for (int i = 0; i < getQuestionList.size(); i++) {
            if (q2.equals(getQuestionList.get(i).getMbwt()) || q3.equals(getQuestionList.get(i).getMbwt())) {
            } else {
                mibaoQ.add(getQuestionList.get(i));
            }
        }
        //显示对话框
        showMiBaoDialog(1);
    }

    // 点击选择问题 2
    @OnClick(R.id.selectQuestion2)
    void setSelectQuestion2() {
        mibaoQ.clear();
        for (int i = 0; i < getQuestionList.size(); i++) {
            if (q1.equals(getQuestionList.get(i).getMbwt()) || q3.equals(getQuestionList.get(i).getMbwt())) {
            } else {
                mibaoQ.add(getQuestionList.get(i));
            }
        }
        //显示对话框
        showMiBaoDialog(2);
    }

    // 点击选择问题 3
    @OnClick(R.id.selectQuestion3)
    void setSelectQuestion3() {
        mibaoQ.clear();
        for (int i = 0; i < getQuestionList.size(); i++) {
            if (q2.equals(getQuestionList.get(i).getMbwt()) || q1.equals(getQuestionList.get(i).getMbwt())) {
            } else {
                mibaoQ.add(getQuestionList.get(i));
            }
        }
        showMiBaoDialog(3);
    }

    /**
     * 显示对话框
     */
    public void showMiBaoDialog(final int question) {
        selectPosition = 0;
        final List<String> list = new ArrayList<>();
        for (int i = 0; i < mibaoQ.size(); i++) {
            list.add(mibaoQ.get(i).getMbwt());
        }
        currentText = list.get(0);

        View wheelDialog = LayoutInflater.from(this).inflate(R.layout.wheel_dialog, null);
        wv = (WheelView) wheelDialog.findViewById(R.id.list_wheel);
        adapter = new CourseListAdapter(this, list, 0, 16, 14);
        wv.setCurrentItem(0);
        wv.setVisibleItems(3);
        wv.setViewAdapter(adapter);

        wv.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                currentText = (String) adapter.getItemText(wheel.getCurrentItem());
                selectPosition = wheel.getCurrentItem();
                setTextviewSize(currentText, adapter);
                currentPosition = wheel.getCurrentItem();
            }
        });
        wv.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                String currentText = (String) adapter.getItemText(wheel.getCurrentItem());
                setTextviewSize(currentText, adapter);
            }
        });
        new MaterialDialog.Builder(this)
                .title("选择密保问题")
                .titleColor(Color.BLACK)
                .customView(wheelDialog, true)
                .backgroundColor(Color.WHITE)
                .positiveColor(getResources().getColor(R.color.colorAccent))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        switch (question) {
                            case 1:
                                //第一个问题
                                question1.setText(list.get(selectPosition));
                                q1 = list.get(selectPosition);
                                break;
                            case 2:
                                //第2个问题
                                question2.setText(list.get(selectPosition));
                                q2 = list.get(selectPosition);
                                break;
                            case 3:
                                //第3个问题
                                question3.setText(list.get(selectPosition));
                                q3 = list.get(selectPosition);
                                break;
                        }

                    }
                })
                .cancelable(true)
                .positiveText(R.string.agree)
                .positiveColor(getResources().getColor(R.color.colorAccent))
                .negativeText(R.string.disagree)
                .negativeColor(getResources().getColor(R.color.color_666))
                .show();
    }

    // 监听输入框都有内容时才可以点击
    @OnTextChanged(value = {R.id.answer1, R.id.answer2, R.id.answer3}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void OnTextChanged() {
        if (StringUtils.isNull(answer1.getText().toString()) ||
                StringUtils.isNull(q1) ||
                StringUtils.isNull(answer2.getText().toString()) ||
                StringUtils.isNull(q2) ||
                StringUtils.isNull(answer3.getText().toString()) ||
                StringUtils.isNull(q3)) {
            btnSend.setEnabled(false);
        } else {
            btnSend.setEnabled(true);
        }
    }


    /**
     * 设置字体大小
     *
     * @param curriteItemText
     * @param adapter
     */
    public void setTextviewSize(String curriteItemText, CourseListAdapter adapter) {
        List<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textview = (TextView) arrayList.get(i);
            currentText = textview.getText().toString();
            if (curriteItemText.equals(currentText)) {
                textview.setTextSize(16);
                textview.setTextColor(getResources().getColor(R.color.color_tv333));
            } else {
                textview.setTextSize(14);
                textview.setTextColor(getResources().getColor(R.color.color_999));
            }
        }
    }

    //设置标题
    @Override
    public String setupToolBarTitle() {
        return "密保问题";
    }

    //设置左边按钮
    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    //返回
    @OnClick(R.id.toolbar_leftbtn)
    void onGoBack() {
        finish();

    }

    String answerOne, answerTwo, answerThree;

    @OnClick(R.id.btn_send)
    void setQuesion() {

        answerOne = answer1.getText().toString().trim();//拿到三个问题答案
        answerTwo = answer2.getText().toString().trim();
        answerThree = answer3.getText().toString().trim();
        if (answerOne.length() <= 50 && answerTwo.length() <= 50 &&
                answerOne.length() <= 50) {
            String data = "{\"1\":{\"mbwt\":\"" + question1.getText().toString().trim() + "\",\"mbda\":\"" + answerOne + "\"},\"2\":{\"mbwt\":\""
                    + question2.getText().toString().trim() + "\",\"mbda\":\"" + answerTwo +
                    "\"},\"3\":{\"mbwt\":\"" + question3.getText().toString().trim() + "\",\"mbda\":\"" + answerThree + "\"}}";
            Log.d("上传的字符串" + data);
            dao.setQuestion(data);
        } else {
            MessageUtils.showImageShortToast(this, "请输入1~50位密保答案");
        }

    }

    // 请求成功
    @Override
    public void onRequestSuccess(int requestCode) {
        super.onRequestSuccess(requestCode);
        if (dao.status.equals("0")) {
            switch (requestCode) {
                case CodeConst.GETQUESTION://获取密保问题
                    getQuestionList.clear();
                    getQuestionList.addAll(dao.getQuestions());
                    break;
                case CodeConst.SETQUESTION://设置密保问题
                    MessageUtils.showRightImageShortToast(this, dao.statusCode);
                    finish();
                    break;
            }
        }
    }


    /**
     * 适配器
     */
    private class CourseListAdapter extends AbstractWheelTextAdapter {
        List<String> list;

        protected CourseListAdapter(Context context, List<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.layout.expand_callname_courselist_item, NO_RESOURCE, currentItem, maxsize, minsize);
            this.list = list;
            setItemTextResource(R.id.tempValue);
        }


        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            TextView textView = (TextView) view.findViewById(R.id.tempValue);
            String textStr = textView.getText().toString();
            if (textStr.equals(currentText)) {
                textView.setTextSize(16);
                textView.setTextColor(getResources().getColor(R.color.color_tv333));
            } else {
                textView.setTextSize(14);
                textView.setTextColor(getResources().getColor(R.color.color_999));
            }
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }
}
